import sys, settings, msgs, time, getopt, getpass, hashlib, hmac, socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

def usage():
	print "whatever"

try:
    	opts, args = getopt.getopt(sys.argv[1:], "ho:a:s:", ["help", "opcode=", "admin=", "store="])
except getopt.GetoptError, err:
    	usage()
    	sys.exit(2)

opCode = apass = server = eFile = None
server = "127.0.0.1"

for o, a in opts:
       	if o in ("-h", "--help"):
     		usage()
      		sys.exit(0)
        elif o in ("-o", "--opcode"):
      		opCode = a
	elif o in ("-a", "--admin"):
		admin = a
	elif o in ("-s", "--store"):
		try:
			storeFD = open(a, "w")
		except:
			print "error opening file for writing key, quiting\r\n"
			sys.exit(1)
        else:
       	    assert False, "unhandled option"

if opCode == "crtserver":
	hostIP = getpass.getpass("IP Address of host:")
	apass = getpass.getpass("Admin Password:")
	strTime = str(time.asctime())

	data = "%s:%s:%s:%s" % (admin, apass, hostIP, strTime)
	
	sh = hashlib.new('sha1')
	sh.update(data)
	serverHash = sh.hexdigest()

	data = "%s:%s" % (hostIP, serverHash)

        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        conn.connect((server, 5023))

        data = "crtserver\r\n%s" % (data)
	
	try:
	        conn.send(data)
	except:
		print "Unable to send data to server\r\n"
		conn.close()
		sys.exit(1)

        #
        # The following two lines will be replaced by manual transfer of file using USB or floppy
	#
	storeFD.write(serverHash)
	storeFD.close()

        conn.close()

